from PyQt4.QtGui import QWidget,QListWidgetItem,QFileDialog
from KUI.KSharedUI.ui_KSelectDataSetWgt import Ui_KSelectDataSetWgt
from PyQt4 import QtCore
from PyQt4.QtCore import QString,Qt,QStringList
from KDataBase.KQueryDB import KQueryDB
import time
import os ;
import re ;
import datetime;
class KSelectDataSetWgt(QWidget):
	''' The UI of strategy batch test '''
	
	OnDataSetChanged=QtCore.pyqtSignal(list)
	
	def __init__(self, parent=None):
		super(KSelectDataSetWgt, self).__init__(parent)
		self.ui =  Ui_KSelectDataSetWgt()    
		self.ui.setupUi(self) 
		
		# setup market options
		counties,markets=KQueryDB.QueryAllCountryMarkets()
		counties.insert(0,'all')
		markets.insert(0,'all')
		[self.ui.CountryCmb.addItem(QString(each_elem.upper())) for each_elem in counties]
		[self.ui.MarketCmb.addItem(QString(each_elem.upper())) for each_elem in markets]
		self.ui.CountryCmb.setCurrentIndex(self.ui.CountryCmb.findText('US'))
		self.ui.MarketCmb.setCurrentIndex(self.ui.MarketCmb.findText('NASDAQ'))
		
		# setup list options
		self.GenerateSymbolListSection()
		# setup signal
		self.ui.BtnGo.clicked.connect(self.OnGoButtonClicked)
		self.ui.rBtn_ByList.setChecked(True)
		
		
	def GetSymbolListByComboIndex(self,index):
		# acquire symbol list of given list index
		if index>self.ui.ListCmb.count()-1:
			return []
		else:
			abspath=self.ui.ListCmb.itemData(index)
			fileobj=open(str(abspath.toString()))
			symbolist=[x.strip('\n') for x in fileobj]
			fileobj.close()
			return symbolist
			
	def GenerateSymbolListSection(self):
		# scan sybmol list folder and add list
		self.ui.ListCmb.clear()
		path=r'D:\Dropbox\Trading2013\KunTrading\ConfigFiles\KSymbolList'
		subfolders = os.listdir(path)
		for sub_dir in subfolders:
			abspath=os.path.join(path, sub_dir)
			if os.path.isfile(abspath):
				self.ui.ListCmb.addItem(sub_dir,abspath)
				
	
	def GetCurrentSymbolList(self):
		if self.ui.rBtn_ByMarket.isChecked():
			# choose by market
			country=self.ui.CountryCmb.currentText()
			market=self.ui.MarketCmb.currentText()
			if country and market:	
				mstocks=KQueryDB.QueryAllStocksStaticInfoByMkt(str(country),str(market)) # also get latest price	
				return mstocks.keys()
		else:
			# choose by symbol list
			itemindex=self.ui.ListCmb.currentIndex()	
			return self.GetSymbolListByComboIndex(itemindex)
	
	def OnGoButtonClicked(self):
		#triggered when 'go' button is clicked
		self.OnDataSetChanged.emit(self.GetCurrentSymbolList())




		
		